package com.smaato.comms;

import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Vector;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;

import net.rim.device.api.system.DeviceInfo;

public class CommsEngine 
{
	private boolean iActive = false;
    private HttpConnection iConnection = null;
    private InputStream iInputStream = null;
    private String iConnectionParam = null;
	
	public CommsEngine()
	{	
	}
	
	public boolean openConnection(String aUrl)throws IOException
	{
		try
        {
			findConnectionString(aUrl);
            iConnection = (HttpConnection)Connector.open(aUrl);
        }
        catch (ClassCastException e)
        {
            throw new IOException("Not an HTTP URL");
        } 
        catch (Exception e)
        {
            throw new IOException("The user probably didn't allow the connection permission");
        }

        if(iConnection != null)
        {
            SetRequestProperties();
        }

        return (iConnection != null);
	}

	private void findConnectionString(String url)
	{
		int index = url.indexOf(";deviceside");
		if(index != -1)
		{
			iConnectionParam = url.substring(index);
		}
	}
	
	public void closeConnection()
	{
		try
        {
            if (iInputStream != null)
            {
                iInputStream.close();
                iInputStream = null;
            }

            if (iConnection != null)
            {
                iConnection.close();
                iConnection = null;
            }

            iActive = false;
        }
        catch (IOException ioe)
        {
        }
	}
	
	private void SetRequestProperties() throws IOException
    {
        // Set the request method and headers
		String userAgentHeader = "Blackberry" + DeviceInfo.getDeviceName() + "/" + DeviceInfo.getSoftwareVersion()
		+ " Profile/" + System.getProperty("microedition.profiles") 
		+ " Configuration/" + System.getProperty("microedition.configuration");

		iConnection.setRequestMethod(HttpConnection.GET);
		iConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		iConnection.setRequestProperty("Accept", "*/*");
		iConnection.setRequestProperty("User-Agent", userAgentHeader);
    }
	
	public String getConnectionHeader(String headerField)throws IOException
	{
		if(iConnection == null)
		{
			throw new IOException("Connnection is null");
		}
		
		return iConnection.getHeaderField(headerField);
	}
	
	public boolean IsConnectionActive()
    {
        return iActive;
    }
	
	public byte[] getData() throws IOException
	{
		if(iConnection == null)
		{
			throw new IOException("connnection is null");
		}

        int responseCode = iConnection.getResponseCode();
        
        if(responseCode == HttpConnection.HTTP_MOVED_TEMP)
        {
        	String redirectUrl = iConnection.getHeaderField("Location") + iConnectionParam;
        	closeConnection();
        	if(openConnection(redirectUrl))
        	{
        		responseCode = iConnection.getResponseCode();
        	}
        	else
        	{
        		throw new IOException("Attempted redirect failed");
        	}
        }
        
        if(responseCode != HttpConnection.HTTP_OK) 
        {
            throw new IOException("HTTP response code: " + responseCode);
        }

        byte[] data;
        iInputStream = new SafeInputStream(iConnection.openInputStream());    
        int len = (int)iConnection.getLength();
        
        if(len > 0) 
        {
        	int actual = 0;
        	int bytesread = 0;
        	data = new byte[len];
        	while ((bytesread != len) && (actual != -1)) 
        	{
        		actual = iInputStream.read(data, bytesread, len - bytesread);
        		bytesread += actual;
        	}
        } 
        else 
        {
        	Vector buffer = new Vector();

        	int ch;
        	while ((ch = iInputStream.read()) != -1)
        	{
        		Byte aByte = new Byte((byte) ch);
        		buffer.addElement(aByte);
        	}

        	data = new byte[buffer.size()];

        	int i = 0;
        	for (Enumeration e = buffer.elements(); e.hasMoreElements(); i++)
        	{
        		Byte nextbyte = (Byte) e.nextElement();
        		data[i] = nextbyte.byteValue();
        	}
        }
        
        return data;
	}
}
